package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;

import com.itheima.exception.MemberDelfailException;
import com.itheima.exception.MemberDelfailException;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/member")
public class MemberController {
    @Reference
    private MemberService memberService;


    @RequestMapping("/add")
    public Result add(@RequestBody Member member) {
        try {
            member.setRegTime(new Date());
            memberService.add(member);
        } catch (Exception e) {
            e.getMessage();
            return new Result(false, MessageConstant.ADD_MEMBER_FAIL);
        }
        return new Result(true, MessageConstant.ADD_MEMBER_SUCCESS);

    }

    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        return memberService.findPage(queryPageBean);
    }

    @RequestMapping("/findById")
    public Result findById(Integer id) {
        try {
            Member member = memberService.findById(id);
            return new Result(true, MessageConstant.EDIT_MEMBER_SUCCESS, member);
        } catch (Exception e) {
            e.getMessage();
            return new Result(false, MessageConstant.EDIT_MEMBER_FAIL);
        }
    }

    //@PreAuthorize("hasAnyAuthority('CHECKITEM_DELETE')") //权限校验
    @RequestMapping("/edit")
    public Result edit(@RequestBody Member member) {
        try {
            memberService.edit(member);
        } catch (Exception e) {
            e.getMessage();
            return new Result(false, MessageConstant.EDIT_MEMBER_FAIL);
        }
        return new Result(true, MessageConstant.EDIT_MEMBER_SUCCESS);
    }

    @RequestMapping("/findAllHealThmanagerName")
    public Result findAllHealThmanagerName() {
        try {
            List<Map<String,String>> mapList = memberService.findAllHealThmanagerName();
            return new Result(true, MessageConstant.EDIT_MEMBER_SUCCESS,mapList);
        } catch (Exception e) {
            e.getMessage();
            return new Result(false, MessageConstant.EDIT_MEMBER_FAIL);
        }
    }

    @RequestMapping("/deleteById")
    public Result deleteById(Integer id) {
        try {
            memberService.deleteById(id);
        } catch (Exception e) {
            e.getMessage();
            if(e instanceof MemberDelfailException){
                return new Result(false, "此会员使用过套餐, 不支持删除！");
            }
            return new Result(false, MessageConstant.DELETE_MEMBER_FAIL);
        }
        return new Result(true, MessageConstant.DELETE_MEMBER_SUCCESS);
    }

    @RequestMapping("/getExcel")
    public void downup(HttpServletRequest request, HttpServletResponse response,String[] memberIds) {
        try {

            //获得Excel模板文件绝对路径
            String temlateRealPath = request.getSession().getServletContext().getRealPath("template") +
                    File.separator + "member.xlsx";
            //读取模板文件创建Excel表格对象
            XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(temlateRealPath)));

            List<Map<String, Object>> list = memberService.findByIds(memberIds);
            XSSFSheet sheet = workbook.getSheetAt(0);

            Integer count = 0;

            for (int i = 0; i < list.size(); i++) {
                Map<String, Object> map = list.get(i);
                Member member =(Member) map.get("member");
                List checkgroups =(List) map.get("checkgroups");
                List checkitems =(List) map.get("checkitems");
                List adderss =(List) map.get("adderss");
                count++;
                XSSFRow row = sheet.createRow(count);

                row.createCell(0).setCellValue(member.getName());
                row.createCell(1).setCellValue(member.getSex());
                row.createCell(2).setCellValue(member.getPhoneNumber());
                row.createCell(3).setCellValue(adderss.toString());//机构地址
                row.createCell(4).setCellValue(map.get("sname").toString());//套餐
                row.createCell(5).setCellValue(checkgroups.toString());//检查组
                row.createCell(6).setCellValue(checkitems.toString());//检查项
            }
            //通过输出流进行文件下载
            /*两个头一个流,通过响应对象获取字节输出流,往浏览器上写数据,并设置两个响应头,给浏览器指定文件类型*/
            ServletOutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition", "attachment;filename=member.xlsx");
            workbook.write(out);
            out.flush();
            out.close();
            workbook.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
